const statusMap = {
  0:'初始化',  
  1:'已获取账号Local，使用LocalStorage登录',
  2:'已获取账号Local，使用LocalStorage登录失败',
  3:'已获取账号Local，使用账号密码登录',
  4:'登录成功，需要切换账号'
}
setTimeout(() => {
  window.location.reload()
}, 120000);
setTimeout(async () => {
  if (webError()) {
    const pluginName = await session.get('pluginName', '')
    const serverName = await session.get('serverName', '')
    const hostCode = await session.get('serverName', '')
    await core.sendMsg(hostCode, hostCode+'插件[' + pluginName + ',服务器:' + serverName + ']出现人机验证或者被封禁,请前往确认');
    return;
  }
  // 页面刷新之后  await statusDiv();  一下就行了
  await statusDiv()

  // 检查登陆
  const isLogin = getIslogin()
  
  // 初始化
  const status = await GetAccountStatus()
  await session.set("msg",statusMap[status])
  // 登录逻辑 这里就是登录页
  if(window.location.href == 'https://www.hmm21.com/e-service/auth/login.do'){
    console.log('登录页')
    await setStatus(3)
    // await setAccountToSession()
    // 已获取账号Local，使用账号密码登录
    // 登录form
    const loginForm = document.querySelector('#esvcLoginForm')
    // 登录页
    if(loginForm){
      // 设置账号到loginForm
      setAccount()
    }
  }else if(status == null){
    await setStatus(0)
    window.location.reload()
  }else if(status == 0){
    console.log('初始化初始化')
    await session.set("msg","初始化初始化")
    await setAccountToSession()
    const a = await getAccountFromSession()
    await setAccountToLocal(a)
  } else if(status == 4){
    await setAccountToSession()
    const a = await getAccountFromSession()
    await setAccountToLocal(a)
  }else if(isLogin && status == 1){
    console.log('已登录')
    await session.set("msg","已登录")
    // 已登录，存信息
    await saveLocalAndCookie()
  }else if(status == 1 && !isLogin) {
    // 已获取账号Local，使用LocalStorage登录失败
    await setStatus(2)
    window.location.reload()
    console.log('已获取账号Local，使用LocalStorage登录失败')
  }else if(status == 2){
    console.log('准备跳转到登录页')
    await session.set("msg","准备跳转到登录页,localStorage,status==2")
    await session.set("msg","已获取账号Local，使用LocalStorage登录失败")
    const logout = document.querySelector('.btn-profile')
    if(logout){
      logout.click()
    }
    const logoutSelect = document.querySelectorAll('.bubble-box .menu-list a')
    if(logoutSelect && logoutSelect[1]){
      logoutSelect[1].click()
    }
  }else if(status == 3){
    console.log('准备跳转到登录页')
    await session.set("msg","准备跳转到登录页,localStorage,status==3")
    await session.set("msg","已获取账号Local，使用LocalStorage登录失败")
    const logout = document.querySelector('.btn-profile')
    if(logout){
      logout.click()
    }
    const logoutSelect = document.querySelectorAll('.bubble-box .menu-list a')
    if(logoutSelect && logoutSelect[1]){
      logoutSelect[1].click()
    }
  }
  clearTimer()
  
  
}, 3000)
const GetAccountStatus = async () => {
  const ob = await session.get('accountStatus' ,'{}')
  return JSON.parse(ob).s
}
const getIslogin = () => {
  const dom = document.querySelector('.gnb-item.profile .bubble-box')
  return !!dom
}
const setAccountToLocal = async (ac) => {
  console.log(ac)
  if(!ac){
    return console.error('没有获取到账号信息!')
  }
  const { otherCache } = ac
  if(otherCache) {
    const obj = JSON.parse(otherCache) 
    const local = obj.localStorage
    console.log('插入local',local)
    
    for (const key in local) {
      localStorage.setItem(key, local[key])
    }
    console.log('存入本地的localStorage',window.localStorage)
    const c = obj.cookies
    console.log('插入cookies',c)

    await session.set("msg","插入cookies,localStorage")
    //设置localStorage 到 目标网站域
    // let message = {"from": "extenstion", "action": "localStorage_set", data: local};
    // window.postMessage(message, "*");

    //设置cookies 到 目标网站域
    sendMsg({action: 'setCookie', data: c})

    setTimeout(async() => {
      await setStatus(1)
      window.location.reload();
    }, 3000);
  }else{
    // 没有otherCache 直接扭转到登陆页
    await session.set("msg","没有otherCache 直接扭转到登陆页")
    const user = document.querySelector('.btn-profile')
    user.click()
    setTimeout(async() => {
      sendMsg({action: 'delCookie'})
      localStorage.clear()
      await setStatus(2)
      window.location.reload();
    }, 3000);
  }
}
const getAccountAndRefreshAccount = async (ac) => {
  if(!ac){
    return console.error('没有获取到账号信息!')
  }
  await setStatus(3)
  // const { apiToken, otherCache } = ac
  console.log(ac,123123)
}
const setStatus = async (s) => {
  return await session.set('accountStatus',JSON.stringify({s}))
}
const saveLocalAndCookie = async () => {
  // 登录成功刷新cookie
  sendMsg({action:"getCookie",domain:'.hmm21.com'})
  console.log('登录成功！！！！！！！！！！！！')
  await session.set("msg","登录成功！！！！！！！！！！！！")
  const a = await getAccountFromSession()
  let local = {}
  for (const key in window.localStorage) {
    const v = localStorage.getItem(key)
    if(v){
      local[key] = v
    }
  }
  setTimeout( async () => {
    const cc = await session.get("cookies", '[]')
    console.log('获取cookies',cc)
    await session.set("msg","获取cookies")
    const apiToken = {
      'Cookie':'',
      'X-Csrf-Token':'',
    }
    const xipt = document.querySelectorAll('#esvcLogoutForm > input')
    if(xipt){
      apiToken['X-Csrf-Token'] = xipt[1].value
    }
    for (let i = 0; i < cc.length; i++) {
      const val = cc[i]
      apiToken['Cookie'] += `${val.name}=${val.value};`
    }
    const pamams = {
      ...a,
      otherCache:JSON.stringify({
        localStorage:local,
        cookies:cc,
      }),
      apiToken: JSON.stringify(apiToken),
    }
    console.log(pamams,'update的数据')
    // 更新账户
    await core.updateAccount(pamams)
  }, 10000);
    // 成功以后切换账号
    // 清空
  setTimeout(() => {
    window.localStorage.clear()
  }, 17000);
  setTimeout(async () => {
    console.log('准备切换账号')
    await session.set("msg","准备切换账号")
    await setStatus(4)
    window.location.reload()
  }, 20000);
}
const setAccountToSession = async () => {
  await session.remove('accountFromServer')
  const pluginName = await session.get("pluginName", null)
  const serverName = await session.get("serverName", null)
  const hostCode = await session.get("hostCode", null)
  const res = await core.getAccount(pluginName, hostCode, serverName);
  console.log('当前账号====>',JSON.stringify(res))
  await session.set("msg","当前账号===>"+res?.data.username)
  await session.set('accountFromServer', JSON.stringify(res?.data))
}


// 获取账号
const getAccountFromSession = async () => {
  const se = await session.get('accountFromServer','{}')
  const o = JSON.parse(se)
  if(typeof o != 'object'){
    return null
  }
  return o
}

// 设置账号到loginForm
const setAccount = async () => {
  const account = await getAccountFromSession()
  console.log('account',account)
  if(!account || !account.username){
    await setAccountToSession()
  }
  const a = await getAccountFromSession()
  console.log(a)
  const elipt = document.querySelector("#userId")
  // elipt.val(a.username)
  elipt.value = a.username
  const pwdipt = document.querySelector("#userPwd")
  pwdipt.value = a.password
  let btn;
  setTimeout( async () => {
    btn = document.querySelector('.btn.large')
    console.log(btn,'登录btn')
    await session.set("msg","准备点击登录btn")
  }, 2000);
  
  
  setTimeout( async () => {
    console.log('触发登录按钮')
    await session.set("msg","触发登录按钮")
    btn.click({})
    await setStatus(1)
    getLoginError(a)
  }, 10000);
}
let timer = null
const getLoginError = (errorAccount) => {
  timer = setInterval(async () => {
    const errorDiv = document.querySelector('#divErrMsg')
    if(errorDiv && errorDiv.innerHTML.indexOf('incorrect') != -1) {
      await core.updateAccount(Object.assign(errorAccount, {
        otherCache: null,
        apiToken: null,
        remark: "plugin_remark_error"
      }))
      
      await session.set("msg","账号密码错误")
      clearTimer()
      await setAccountToSession()
      window.location.reload()
    }
  }, 5000);
}
const clearTimer = () => {
  clearInterval(timer)
  timer = null
}


async function statusDiv() {
  let account = await session.get("account", {});
  let cocDiv = document.getElementById("cocDiv");
  if (!!!cocDiv) {

      let div = document.createElement('div');
      div.id = 'cocDiv';
      document.body.appendChild(div);
      const obj = {
        'position': 'absolute',
        'background': '#f1ecec',
        'top': '130px',
        'left': '15px',
        'width': '260px',
        'height': '280px',
        'border': 'solid 5px rgba(16,126,213,0.9)',
        'display': 'flex',
        'align-items': 'center',
        'flex-direction': 'column',
        'font-size': '11px',
        'font-weight': '400',
        'padding': '10px',
        'box-shadow': '4px 2px 1px 0px rgba(16,150,213,0.4)',
        'cursor': 'pointer',
        'z-index': 99999
      }
      for (const key in obj) {
        div.style[key] = obj[key]
      }

      let drag = document.createElement("script");
      drag.append("var draggableNode = document.getElementById('cocDiv');draggableNode.addEventListener('mousedown', function(event) {    var originBoxX = draggableNode.offsetLeft;    var originBoxY = draggableNode.offsetTop;    var mouseX = event.pageX;    var mouseY = event.pageY;    function moveListener(event){        var distanceX = event.pageX - mouseX;        var distanceY = event.pageY - mouseY;        draggableNode.style.left = originBoxX + distanceX + 'px';        draggableNode.style.top = originBoxY + distanceY + 'px';    }    window.addEventListener('mousemove', moveListener);    draggableNode.addEventListener('mouseup', function(event) {        window.removeEventListener('mousemove', moveListener);    });});");
      document.body.append(drag);
      
      div.insertAdjacentHTML('beforeend', '<div style="font-size: 13px;font-weight: 600; margin-bottom: 10px;width: 100%;text-align: center;background: #287ab5;color: white; user-select: none;">>>爬虫插件<<</div>')
      div.insertAdjacentHTML('beforeend', '<div style="width: 100%;text-align: left; margin-bottom: 5px;"><span style="box-shadow: 2px 2px 1px -1px #287ab5;background: rgba(27, 86, 173, 0.3);user-select: none;">账号:</span><span id="account" style="padding-left: 10px;font-weight: 300;text-decoration: underline;text-underline-offset: 3px;">' + account['username'] + '</span></div>')
      div.insertAdjacentHTML('beforeend', '<div style="margin-top: 20px;display: flex; flex-direction: row;user-select: none;width: 100%;margin-left: 5px;"><div style="position: absolute; left: 10px;"><span style="color: red">-></span></div><div id="msg" style="margin-left: 10px;font-weight: 500;color: red"></div></div>')
  }
}

//更新悬浮窗口提示信息
setInterval(async function () {

  let msg = await session.get("msg", "")
  let account = await getAccountFromSession()
  document.querySelector("#msg").innerHTML = msg
  document.querySelector("#account").innerHTML = account['username']

  let pluginName = await session.get("pluginName", null)
  if (!!!pluginName) {
    document.querySelector('#msg').innerHTML = "请先配置插件名和机器名称，进行配对"
  }

}, 1000)